//
//  KLBookDBHelper.m
//  KLBookStore
//
//  Created by apple on 2017/10/15.
//  Copyright © 2017年 NetEaseExam. All rights reserved.
//

#import "KLBookDBHelper.h"

#import "FMDatabase.h"

@implementation KLBookDBHelper

+ (NSString *)dbFolder {
    NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [documentsDir stringByAppendingString:@"/db"];
    return path;
}

+ (NSString *)dbPath {
    NSString *path = [[[self class] dbFolder] stringByAppendingString:@"/book.sqlite"];
    return path;
}

+ (void)buildDataBase {
    if (![[NSFileManager defaultManager] fileExistsAtPath:[[self class] dbFolder]]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:[[self class] dbFolder] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    FMDatabase *db = [FMDatabase databaseWithPath:[[self class] dbPath]];
    if (![db open]) {
        return;
    }
    
    BOOL success = [[self class] createTableWithDB:db];
    if (success) {
        NSLog(@"init sql done");
    } else {
        NSLog(@"init sql fail");
    }
    [db close];
}

+ (BOOL)createTableWithDB:(FMDatabase *)db{
    BOOL success = YES;
    NSArray *array = [[self class] createTableSqls];
    for (NSString *sql in array) {
        if (![db executeUpdate:sql]) {
            success = NO;
            break;
        }
    }
    return success;
}

+ (NSArray *)createTableSqls{
    
    return @[
             @"create table 'TB_BOOK_ENTITY' ( 'id' integer primary key autoincrement, 'doubanId' integer unique, 'isbn10' text, 'isbn13' text, 'title' text, 'doubanUrl' text, 'image' text, 'publisher' text, 'price' text, 'pubdate' text, 'summary' text, 'author_intro' text);",
             @"create table 'TB_BOOK_TRANSLATOR' ('bookId' integer, 'name' text);",
             @"create table 'TB_BOOK_AUTHOR' ('bookId' integer, 'name' text);",
             @"create table 'TB_BOOK_TAG' ('bookId' integer, 'name' text, 'count' integer);"
             ];
}

@end
